package com.lyc.interceptors;

import com.lyc.utils.JwtUtil;
import com.lyc.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Configuration//  配置类，
public class LoginIntercollegiate implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对于OPTIONS预检请求直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        
        //令牌验证
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7).trim(); // 去掉 Bearer 和前后空格
        }
//        System.out.println("token:"+token);
        //  验证token
        try {
            //从redis中获取token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = null;
            if (token != null) {
                redisToken = operations.get(token);
            }
//            System.out.println("redisToken:"+redisToken);
            if (redisToken == null){
                //token已经失效了
//                System.out.println("token已经失效了");
                throw new RuntimeException("用户未登录");
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据保存到ThreadLocal
            ThreadLocalUtil.set(claims);
            //放行到控制器
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal
        ThreadLocalUtil.remove();
    }
}